using com.google.zxing;
using com.google.zxing.common;
using com.google.zxing.qrcode;
using MicroMsg.Common.Event;
using MicroMsg.Common.Utils;
using MicroMsg.Network;
using MicroMsg.Protocol;
using MicroMsg.Resource.@string;
using MicroMsg.Scene;
using MicroMsg.UI.UserContrl;
using MicroMsg.UI.Util;
using Microsoft.Devices;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
namespace MicroMsg.UI.Page
{
	public class ScanQRCodePage : BasePage
	{
		private const string TAG = "ScanQRCodePage";
		private const uint cNScanLineAniDuaration = 3000u;
		private const string PATTERN_STRINGS = "(?is)(http|ftp|https)://(\\w+[\\./]?)*(\\.(html|htm|aspx|asp|php))?[\\w\\?\\=&%]*";
		private const string URL_MM_QRCODE_HEAD_WEIXIN = "weixin://qr/";
		private const string URL_MM_QRCODE_HEAD_HTTP = "http://weixin.qq.com/r/";
		private const string URL_MM_QRCODE_WEB_WX = "https://login.weixin.qq.com/l";
		private const string URL_MM_QRCODE_WEB_WX_OUTER = "https://login.wechatapp.com/l";
		private EventWatcher mWatchSearchContact;
		private object mObjectWatcher = new object();
		private DispatcherTimer _timer;
		private PhotoCameraLuminanceSource _luminance;
		private QRCodeReader _reader;
		private bool mBIsScanStarted;
		private int timerCnt;
		private PhotoCamera _photoCamera;
		private bool mBIsShowCamaraStarted;
		private bool mBIsCamareOk;
		private int mNCameraW;
		private int mNCameraH;
		private bool mBIsChosePicStarted;
		private ApplicationBar mBar;
		private Storyboard mSbScanLine;
		private string TAG_QRCODE = "@qr";
		private string mStrUrl = "";
		private bool mBIsScanEnabled;
		private bool mBIsReqConStarted;
		private int mNTargetW;
		private int mNTargetH;
		private int mNTargetPosX;
		private int mNTargetPosY;
		private byte[] mBytesDatas;
		private int mNCutImgW = 430;
		private int mNCutImgH = 430;
		internal Grid LayoutRoot;
		internal Rectangle _previewRect;
		internal VideoBrush _previewVideo;
		internal CompositeTransform _previewTransform;
		internal Grid borderScanArea;
		internal Grid gridScan;
		internal Image rectScanLine;
		internal TextBlock txtQRCodeScanTip;
		internal Image imgCut;
		private bool _contentLoaded;
		public ScanQRCodePage()
		{
			this.InitializeComponent();
			base.add_Loaded(new RoutedEventHandler(this.Page_Loaded));
			base.add_Unloaded(new RoutedEventHandler(this.Page_Unloaded));
			this.setAppBar();
		}
		private void Page_Loaded(object sender, RoutedEventArgs e)
		{
		}
		private void Page_Unloaded(object sender, RoutedEventArgs e)
		{
		}
		protected override void OnPageIn(object[] object_0)
		{
			Log.smethod_5("ScanQRCodePage", "OnPageIn");
			this.initUI();
			this.registerEvent();
			if (object_0 != null && object_0.Length > 0)
			{
				string text = object_0[0] as string;
				if ("WebMM" == text)
				{
					this.txtQRCodeScanTip.set_Text(strings.WebMM_LoginQRDescr);
				}
			}
		}
		protected override void OnPageOut()
		{
			Log.smethod_5("ScanQRCodePage", "OnPageOut");
			this.unRegisterEvent();
			this.stopScan();
			this._previewVideo = null;
			this._previewRect.set_Fill(new SolidColorBrush());
			this.stopScanLineAni();
			this._previewVideo = null;
			this.stopShowCamara();
			base.get_Dispatcher().BeginInvoke(delegate
			{
				GC.Collect();
			});
		}
		protected override void OnPageForward(Uri targetPage)
		{
			Log.smethod_5("ScanQRCodePage", "OnPageForward");
			Log.smethod_5("ScanQRCodePage", "Page_Unloaded");
			this.stopScan();
			this.stopShowCamara();
		}
		protected override void OnPageBack()
		{
			Log.smethod_5("ScanQRCodePage", "OnPageBack");
			if (this.mBIsChosePicStarted)
			{
				this.startScan();
			}
			this.startShowCamara();
		}
		private void registerEvent()
		{
			if (this.mWatchSearchContact == null)
			{
				this.mWatchSearchContact = new EventWatcher(this.mObjectWatcher, null, new EventHandlerDelegate(this.OnSearchContact));
				EventCenter.registerEventWatcher(EventConst.ON_NETSCENE_SEARCHCONTACT_SUCCESS, this.mWatchSearchContact);
				EventCenter.registerEventWatcher(EventConst.ON_NETSCENE_SEARCHCONTACT_ERR, this.mWatchSearchContact);
			}
		}
		private void unRegisterEvent()
		{
			if (this.mWatchSearchContact != null)
			{
				EventCenter.removeEventWatcher(EventConst.ON_NETSCENE_SEARCHCONTACT_SUCCESS, this.mWatchSearchContact);
				EventCenter.removeEventWatcher(EventConst.ON_NETSCENE_SEARCHCONTACT_ERR, this.mWatchSearchContact);
				this.mWatchSearchContact = null;
			}
		}
		private void OnSearchContact(EventWatcher watcher, BaseEventArgs evtArgs)
		{
			if (this.isReqingCon() && evtArgs != null)
			{
				switch (evtArgs.mEventID)
				{
				case EventConst.ON_NETSCENE_SEARCHCONTACT_ERR:
				{
					this.stopReqCon();
					RetConst retConst = (RetConst)evtArgs.mObject;
					if (retConst == RetConst.MM_ERR_CLIENT)
					{
						MMMessageBox.Show(strings.Reg_PhoneV_MsgBadNet, true, "确定");
						return;
					}
					MMMessageBox.Show(strings.FF_SearchFriendNoUser, true, "确定");
					break;
				}
				case EventConst.ON_NETSCENE_SEARCHCONTACT_SUCCESS:
					base.get_Dispatcher().BeginInvoke(delegate
					{
						this.stopReqCon();
						this.disableScan();
					});
					if (evtArgs.checkType<SearchContactInfo>())
					{
						SearchContactInfo searchContactInfo = evtArgs.mObject as SearchContactInfo;
						ContactDetailViewForAll.GotoContactDitailView(searchContactInfo, ContactDetailFromType.FROM_QRCODE, false);
						return;
					}
					break;
				default:
					return;
				}
				return;
			}
		}
		private void initUI()
		{
			this.enableScan();
			this.startShowCamara();
		}
		private void startScan()
		{
			if (!this.mBIsCamareOk)
			{
				return;
			}
			this.enableScan();
			this.mBIsScanStarted = true;
			if (this._timer == null)
			{
				this._timer = new DispatcherTimer();
				this._timer.set_Interval(TimeSpan.FromMilliseconds(250.0));
			}
			this._timer.add_Tick(new EventHandler(this._timer_Tick));
			this._timer.Start();
		}
		private void _timer_Tick(object sender, EventArgs e)
		{
			if (this.timerCnt % 16 == 0 && this._photoCamera != null)
			{
				try
				{
					if (this._photoCamera.get_IsFocusAtPointSupported())
					{
						this._photoCamera.FocusAtPoint(0.5, 0.5);
					}
					else
					{
						this._photoCamera.Focus();
					}
				}
				catch
				{
				}
			}
			this.timerCnt++;
			if (!this.canScan())
			{
				return;
			}
			try
			{
				if (this._luminance != null && this._luminance.PreviewBufferY != null)
				{
					this.setPixelsToScaner(this._luminance);
					HybridBinarizer hybridBinarizer = new HybridBinarizer(this._luminance);
					if (hybridBinarizer != null)
					{
						BinaryBitmap binaryBitmap = new BinaryBitmap(hybridBinarizer);
						if (binaryBitmap != null)
						{
							Result result = this._reader.decode(binaryBitmap);
							this.proScanResult(result.get_Text());
						}
					}
				}
			}
			catch
			{
			}
		}
		private void stopScan()
		{
			this.disableScan();
			this.mBIsScanStarted = false;
			if (this._timer != null)
			{
				this._timer.remove_Tick(new EventHandler(this._timer_Tick));
				this._timer.Stop();
			}
		}
		private void startShowCamara()
		{
			if (this.mBIsShowCamaraStarted)
			{
				return;
			}
			if (this._photoCamera != null)
			{
				this.stopShowCamara();
			}
			this.mBIsShowCamaraStarted = true;
			if (!Camera.IsCameraTypeSupported(0))
			{
				MMMessageBox.Show(strings.CameraNotSupport, true, "确定");
				return;
			}
			try
			{
				this._photoCamera = new PhotoCamera();
				this._photoCamera.add_Initialized(new EventHandler<CameraOperationCompletedEventArgs>(this._photoCamera_Initialized));
				CameraVideoBrushExtensions.SetSource(this._previewVideo, this._photoCamera);
				CameraButtons.add_ShutterKeyHalfPressed(new EventHandler(this.CameraButtons_ShutterKeyHalfPressed));
			}
			catch
			{
				MMMessageBox.Show(strings.InitCameraFailed, true, "确定");
			}
		}
		private void CameraButtons_ShutterKeyHalfPressed(object sender, EventArgs e)
		{
			if (this._photoCamera != null)
			{
				try
				{
					this._photoCamera.Focus();
				}
				catch
				{
				}
			}
		}
		private void _photoCamera_Initialized(object sender, CameraOperationCompletedEventArgs e)
		{
			if (sender != this._photoCamera)
			{
				return;
			}
			if (e.get_Succeeded() && this._photoCamera != null)
			{
				Size arg_38_0 = this._photoCamera.get_PreviewResolution();
				int width;
				int height;
				try
				{
					width = Convert.ToInt32(this._photoCamera.get_PreviewResolution().get_Width());
					height = Convert.ToInt32(this._photoCamera.get_PreviewResolution().get_Height());
					this._photoCamera.set_FlashMode(2);
				}
				catch
				{
					return;
				}
				this._reader = new QRCodeReader();
				this.mBIsCamareOk = true;
				base.get_Dispatcher().BeginInvoke(delegate
				{
					if (this._photoCamera == null)
					{
						return;
					}
					this._previewTransform.set_Rotation(this._photoCamera.get_Orientation());
					if (this._photoCamera.get_Orientation() == 90.0)
					{
						this._previewRect.set_Height((double)width);
						this._previewRect.set_Width((double)height);
						this.mNCameraH = width;
						this.mNCameraW = height;
					}
					else
					{
						this._previewRect.set_Height((double)height);
						this._previewRect.set_Width((double)width);
						this.mNCameraH = height;
						this.mNCameraW = width;
					}
					this.startScan();
				});
				base.get_Dispatcher().BeginInvoke(delegate
				{
					this._luminance = this.getLumiance((double)width, (double)height);
				});
				return;
			}
			base.get_Dispatcher().BeginInvoke(delegate
			{
				MMMessageBox.Show(strings.InitCameraFailed, true, "确定");
			});
		}
		private void stopShowCamara()
		{
			if (this._photoCamera != null)
			{
				this._photoCamera.Dispose();
				this._photoCamera.remove_Initialized(new EventHandler<CameraOperationCompletedEventArgs>(this._photoCamera_Initialized));
				this._photoCamera = null;
			}
			CameraButtons.remove_ShutterKeyHalfPressed(new EventHandler(this.CameraButtons_ShutterKeyHalfPressed));
			this.mBIsShowCamaraStarted = false;
		}
		private void releaseCover()
		{
			ProcessingCover.releaseProgressBar(this.LayoutRoot);
		}
		private void getCover(string strToShow)
		{
			ProcessingCover.getProgressBar(this.LayoutRoot, strToShow, null, false, false, null);
		}
		private void startChosePic()
		{
			if (BasePage.CanDoBackSysTask())
			{
				BasePage.DoBackSysTask();
				this.stopScan();
				PhotoChooserTask photoChooserTask = new PhotoChooserTask();
				photoChooserTask.add_Completed(new EventHandler<PhotoResult>(this.photoTask_Completed));
				photoChooserTask.set_PixelHeight(480);
				photoChooserTask.set_PixelWidth(480);
				photoChooserTask.Show();
				this.mBIsChosePicStarted = true;
				return;
			}
		}
		private void photoTask_Completed(object sender, PhotoResult photoResult_0)
		{
			base.get_Dispatcher().BeginInvoke(delegate
			{
				this.stopChosePic();
			});
			this.disableScan();
			if (photoResult_0.get_Error() != null)
			{
				base.get_Dispatcher().BeginInvoke(delegate
				{
					MMMessageBox.Show(strings.Set_Personal_CanNotLoadImages, true, "确定");
				});
				BasePage.EnableBackSysTask();
				this.enableScan();
				return;
			}
			if (photoResult_0.get_TaskResult() == 1)
			{
				BitmapImage bitmapImage = new BitmapImage();
				bitmapImage.SetSource(photoResult_0.get_ChosenPhoto());
				WriteableBitmap writeableBitmap = new WriteableBitmap(bitmapImage);
				try
				{
					PhotoCameraLuminanceSource photoCameraLuminanceSource = new PhotoCameraLuminanceSource(writeableBitmap.get_PixelWidth(), writeableBitmap.get_PixelHeight());
					for (int i = 0; i < writeableBitmap.get_Pixels().Length; i++)
					{
						byte[] bytes = BitConverter.GetBytes(writeableBitmap.get_Pixels()[i]);
						if (bytes.Length == 4)
						{
							photoCameraLuminanceSource.PreviewBufferY[i] = (bytes[1] * 30 + bytes[2] * 59 + bytes[3] * 11) / 100;
						}
					}
					HybridBinarizer hybridBinarizer = new HybridBinarizer(photoCameraLuminanceSource);
					if (hybridBinarizer != null)
					{
						BinaryBitmap binaryBitmap = new BinaryBitmap(hybridBinarizer);
						if (binaryBitmap != null)
						{
							Result result = this._reader.decode(binaryBitmap);
							this.proScanResult(result.get_Text());
						}
					}
				}
				catch
				{
					this.enableScan();
					base.get_Dispatcher().BeginInvoke(delegate
					{
						MMMessageBox.Show(strings.FF_QRCode_NotFound, true, "确定");
					});
				}
			}
		}
		private void stopChosePic()
		{
			this.mBIsChosePicStarted = false;
			this.startScan();
		}
		private ApplicationBar setAppBar()
		{
			if (this.mBar != null)
			{
				if (!this.mBar.get_IsVisible())
				{
					this.mBar.set_IsVisible(true);
				}
				return this.mBar;
			}
			this.mBar = new ApplicationBar();
			this.mBar.set_IsMenuEnabled(true);
			this.mBar.set_IsVisible(true);
			ApplicationBarIconButton applicationBarIconButton = new ApplicationBarIconButton(new Uri("/Source/Plugin/QRCode/Resource/myQRCode_icon.png", 2));
			applicationBarIconButton.set_Text(strings.FF_QRCode_MyQRCode.Replace(" Code", ""));
			applicationBarIconButton.add_Click(new EventHandler(this.btnMyQRCode_Click));
			this.mBar.get_Buttons().Add(applicationBarIconButton);
			applicationBarIconButton = new ApplicationBarIconButton(new Uri("/Source/Plugin/QRCode/Resource/picturelib_icon.png", 2));
			applicationBarIconButton.set_Text(strings.FF_QRCode_Choose_Photo);
			applicationBarIconButton.add_Click(new EventHandler(this.btnFromPicLib_Click));
			this.mBar.get_Buttons().Add(applicationBarIconButton);
			ApplicationBarMenuItem applicationBarMenuItem = new ApplicationBarMenuItem(strings.SyncPhoneContact_UserInstruction);
			applicationBarMenuItem.add_Click(new EventHandler(this.btnMenu_Click));
			this.mBar.get_MenuItems().Add(applicationBarMenuItem);
			base.set_ApplicationBar(this.mBar);
			this.setAppBarStyle(base.get_ApplicationBar());
			return this.mBar;
		}
		private void btnMyQRCode_Click(object sender, EventArgs e)
		{
			ToolFunction.GotoPageForUserControl("/Source/Plugin/QRCode/UI/UserQRCodePage.xaml", null, false);
		}
		private void btnFromPicLib_Click(object sender, EventArgs e)
		{
			this.startChosePic();
		}
		private void btnMenu_Click(object sender, EventArgs e)
		{
			ToolFunction.GotoPageForUserControl("/Source/Plugin/QRCode/UI/QRCodeGuidePage.xaml", null, false);
		}
		private void startScanLineAni()
		{
			CompositeTransform compositeTransform = new CompositeTransform();
			this.rectScanLine.set_RenderTransform(compositeTransform);
			this.rectScanLine.set_RenderTransformOrigin(new Point(0.5, 0.5));
			Storyboard storyboard = new Storyboard();
			DoubleAnimation doubleAnimation = this.createAnimation(0.0, this.borderScanArea.get_Height(), compositeTransform, "TranslateY", 3000u);
			doubleAnimation.set_AutoReverse(true);
			doubleAnimation.set_RepeatBehavior(RepeatBehavior.get_Forever());
			storyboard.get_Children().Add(doubleAnimation);
			this.mSbScanLine = storyboard;
			this.mSbScanLine.add_Completed(new EventHandler(this.mSbScanLine_Completed));
			this.mSbScanLine.Begin();
		}
		private void mSbScanLine_Completed(object sender, EventArgs e)
		{
		}
		private void stopScanLineAni()
		{
			if (this.mSbScanLine != null)
			{
				this.mSbScanLine.Stop();
			}
			this.mSbScanLine = null;
			this.rectScanLine.set_RenderTransform(null);
		}
		private void pauseScanLineAni()
		{
			if (this.mSbScanLine != null)
			{
				this.mSbScanLine.Pause();
			}
		}
		private void resumeScanLineAni()
		{
			if (this.mSbScanLine != null)
			{
				this.mSbScanLine.Resume();
				return;
			}
			this.startScanLineAni();
		}
		private DoubleAnimation createAnimation(double from, double double_0, DependencyObject target, string property, uint duration)
		{
			new Storyboard();
			DoubleAnimation doubleAnimation = new DoubleAnimation();
			doubleAnimation.set_From(new double?(from));
			doubleAnimation.set_To(new double?(double_0));
			doubleAnimation.set_Duration(TimeSpan.FromMilliseconds(duration));
			Storyboard.SetTarget(doubleAnimation, target);
			Storyboard.SetTargetProperty(doubleAnimation, new PropertyPath(property, new object[0]));
			return doubleAnimation;
		}
		protected override void OnBackKeyPress(CancelEventArgs cancelEventArgs_0)
		{
		}
		private void proScanResult(string strResult)
		{
			if (this.isReqingCon())
			{
				return;
			}
			if (string.IsNullOrEmpty(strResult))
			{
				return;
			}
			Match match = Regex.Match(strResult, "(?is)(http|ftp|https)://(\\w+[\\./]?)*(\\.(html|htm|aspx|asp|php))?[\\w\\?\\=&%]*");
			if (!match.get_Success())
			{
				string text = string.Format(strings.FF_QRCode_Unknow, strResult);
				if (!string.IsNullOrEmpty(text))
				{
					this.disableScan();
					MMMessageBox mMMessageBox = MMMessageBox.Show(text, true, "确定");
					mMMessageBox.ReturnEvent = new DlgReturnEvent(this.msgBoxOpenUrlHandler);
				}
				return;
			}
			string text2;
			if (strResult.Contains("weixin://qr/"))
			{
				text2 = strResult.Substring("weixin://qr/".get_Length());
			}
			else
			{
				if (strResult.Contains("http://weixin.qq.com/r/"))
				{
					text2 = strResult.Substring("http://weixin.qq.com/r/".get_Length());
				}
				else
				{
					if (!strResult.Contains("https://login.weixin.qq.com/l") && !strResult.Contains("https://login.wechatapp.com/l"))
					{
						if (strResult.get_Length() < match.get_Index() + match.get_Length())
						{
							return;
						}
						this.disableScan();
						this.mStrUrl = strResult.Substring(match.get_Index(), match.get_Length());
						ToolFunction.GotoWebLinkInWebView(this.mStrUrl, GetA8KeyScene.MMGETA8KEY_SCENE_QRCODE);
						return;
					}
					else
					{
						this.disableScan();
						if (!NetworkDeviceWatcher.isNetworkAvailable())
						{
							MMMessageBox.Show(strings.Login_Main_MsgBadNet, true, "确定").ReturnEvent = new DlgReturnEvent(this.finishPage);
							return;
						}
						this.mStrUrl = strResult.Substring(match.get_Index(), match.get_Length());
						Log.smethod_5("ScanQRCodePage", "before get A8Key url = " + this.mStrUrl);
						new NetSceneGetA8Key().doScene(this.mStrUrl, GetA8KeyScene.MMGETA8KEY_SCENE_QRCODE, new DelegateNavigateToUrl(this.navigateToUrl), GetA8KeyOpCode.MMGETA8KEY_REDIRECT);
						return;
					}
				}
			}
			if (!string.IsNullOrEmpty(text2))
			{
				this.startReqCon();
				ServiceCenter.sceneSearchContact.doScene(text2 + this.TAG_QRCODE);
			}
		}
		public void msgBoxDefaultHandler(DlgReturnEventArg dlgReturnEventArg_0)
		{
			this.enableScan();
		}
		private void finishPage(DlgReturnEventArg dlgReturnEventArg_0)
		{
			this.startScan();
		}
		public void msgBoxOpenUrlHandler(DlgReturnEventArg dlgReturnEventArg_0)
		{
			this.enableScan();
			if (string.IsNullOrEmpty(this.mStrUrl))
			{
				return;
			}
			if (MMMessageBox.GetUserClickResult(dlgReturnEventArg_0) == 0)
			{
				ToolFunction.GotoWebLink(this.mStrUrl);
			}
		}
		private void navigateToUrl(string string_0)
		{
			WebMMLoginPage.GotoThisPage(string_0);
		}
		private void enableScan()
		{
			this._previewRect.set_Visibility(0);
			this.resumeScanLineAni();
			this.mBIsScanEnabled = true;
		}
		private void disableScan()
		{
			this._previewRect.set_Visibility(1);
			this.pauseScanLineAni();
			this.mBIsScanEnabled = false;
		}
		private bool canScan()
		{
			return this.mBIsScanEnabled;
		}
		private void startReqCon()
		{
			this.getCover(strings.FF_QRCode_Searching);
			this.disableScan();
			this.mBIsReqConStarted = true;
		}
		private void stopReqCon()
		{
			this.releaseCover();
			this.enableScan();
			this.mBIsReqConStarted = false;
		}
		private bool isReqingCon()
		{
			return this.mBIsReqConStarted;
		}
		private PhotoCameraLuminanceSource getLumiance(double dOriginW, double dOriginH)
		{
			return new PhotoCameraLuminanceSource((int)dOriginW, (int)dOriginH);
		}
		private void setPixelsToScaner(PhotoCameraLuminanceSource lumiance)
		{
			if (lumiance != null && this._photoCamera != null)
			{
				this._photoCamera.GetPreviewBufferY(this._luminance.PreviewBufferY);
				return;
			}
		}
		[DebuggerNonUserCode]
		public void InitializeComponent()
		{
			if (this._contentLoaded)
			{
				return;
			}
			this._contentLoaded = true;
			Application.LoadComponent(this, new Uri("/MicroMsg;component/Source/Plugin/QRCode/UI/ScanQRCodePage.xaml", 2));
			this.LayoutRoot = (Grid)base.FindName("LayoutRoot");
			this._previewRect = (Rectangle)base.FindName("_previewRect");
			this._previewVideo = (VideoBrush)base.FindName("_previewVideo");
			this._previewTransform = (CompositeTransform)base.FindName("_previewTransform");
			this.borderScanArea = (Grid)base.FindName("borderScanArea");
			this.gridScan = (Grid)base.FindName("gridScan");
			this.rectScanLine = (Image)base.FindName("rectScanLine");
			this.txtQRCodeScanTip = (TextBlock)base.FindName("txtQRCodeScanTip");
			this.imgCut = (Image)base.FindName("imgCut");
		}
	}
}
